package map_set.leetcode.medium;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author bruin_du
 * @description 神奇的字典
 * @date 2022/8/18 21:46
 **/
//广义邻居家哈希表解法，感觉还是可以，但是这道题还不如用暴力
public class OfferII064_MagicDictionary {
    Set<String> set;
    Map<String, Integer> map;

    /** Initialize your data structure here. */
    public OfferII064_MagicDictionary() {
        set = new HashSet<>();
        map = new HashMap<>();
    }

    public String[] getNeighbors(String str) {
        StringBuilder sb = new StringBuilder(str);
        String[] strings = new String[str.length()];
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            sb.setCharAt(i, '*');
            strings[i] = sb.toString();
            sb.setCharAt(i, ch);
        }
        return strings;
    }

    public void buildDict(String[] dictionary) {
        for (String strDict : dictionary) {
            set.add(strDict);
            for (String strNeig : getNeighbors(strDict)) {
                map.put(strNeig, map.getOrDefault(strNeig, 0) + 1);
            }
        }
    }

    public boolean search(String searchWord) {
        for (String str : getNeighbors(searchWord)) {
            int num = map.getOrDefault(str, 0);
            if (num > 1 || num == 1 && !set.contains(searchWord)) return true;
        }
        return false;
    }
}

//暴力法
class MagicDictionary {
    private String[] words;

    public MagicDictionary() {

    }

    public void buildDict(String[] dictionary) {
        words = dictionary;
    }

    public boolean search(String searchWord) {
        for (String word : words) {
            if (word.length() != searchWord.length()) {
                continue;
            }

            int diff = 0;
            for (int i = 0; i < word.length(); ++i) {
                if (word.charAt(i) != searchWord.charAt(i)) {
                    ++diff;
                    if (diff > 1) {
                        break;
                    }
                }
            }
            if (diff == 1) {
                return true;
            }
        }
        return false;
    }
}
